package com.dalei.vdserver.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.dalei.vdserver.model.User;

public class UserDaoImpl extends JdbcDaoSupport implements UserDao {

	@Override
	@SuppressWarnings("unchecked")
	public List<User> getUsers() {
		// TODO Auto-generated method stub
		final String sql = "SELECT * FROM vds_user ORDER BY _user";
		List<User> users = null;
		try {
			users = getJdbcTemplate().query(sql, new RowMapper() {

				@Override
				public Object mapRow(ResultSet rs, int rowNum)
						throws SQLException {
					// TODO Auto-generated method stub
					User user = new User();
					user.setId(rs.getInt("_id"));
					user.setUserName(rs.getString("_user"));
					user.setPassword(rs.getString("_password"));
					Timestamp timestamp = rs.getTimestamp("_createdTime");
					Date createdTime = new Date(timestamp.getTime());
					user.setCreatedTime(createdTime);
					return user;
				}
			});
		} catch (DataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
		return users;
	}

	@Override
	public User getUserByUserName(final String userName) {
		// TODO Auto-generated method stub
		final String sql = "SELECT * FROM vds_user WHERE _user=?";
		User user = null;
		try {
			user = (User) getJdbcTemplate().queryForObject(sql,
					new Object[] { userName }, new RowMapper() {

						@Override
						public Object mapRow(ResultSet rs, int rowNum)
								throws SQLException {
							// TODO Auto-generated method stub
							User u = new User();
							u.setId(rs.getInt("_id"));
							u.setUserName(rs.getString("_user"));
							u.setPassword(rs.getString("_password"));
							Timestamp timestamp = rs
									.getTimestamp("_createdTime");
							Date createdTime = new Date(timestamp.getTime());
							u.setCreatedTime(createdTime);
							return u;
						}
					});
		} catch (IncorrectResultSizeDataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		} catch (DataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
		return user;
	}
}
